package member

import (
	"context"
	"group-buy/group_buy/internal/models"
	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveLogic {
	return &SaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveLogic) Save(req *types.Member) (resp *types.Member, err error) {
	m := &models.Member{
		Id:     req.Id,
		Name:   req.Name,
		Phone:  req.Phone,
		Cover:  req.Cover,
		OpenId: req.OpenId,
		Role:   1,
	}
	if m.Id > 0 {
		lsUser := &models.LsUserInfo{UserId: req.Id}
		_, _ = l.svcCtx.Engine.Get(lsUser)
		lsCard := &models.LsCardInfo{UserId: req.Id}
		_, _ = l.svcCtx.Engine.Get(lsCard)

		m.LsUser = lsUser.ChannelUser
		m.LsCard = lsCard.CardId
		_, err = l.svcCtx.Engine.ID(m.Id).Update(m)
		if err != nil {
			return nil, err
		}
	} else {
		_, err = l.svcCtx.Engine.Insert(m)
		if err != nil {
			return nil, err
		}
	}
	req.Id = m.Id
	return req, nil
}
